﻿using System;
using System.Text;
using System.Data;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using Microsoft.Win32;

namespace Utilities
{
    public class clsMethod4All
    {
        #region Method Lâm viết

        #region Method for Listview
        //Tạo cột cho listview, dùng để sort
        public void CreateColHeader(ListView ListviewName, string[] ColumnName, int[] ColumnWidth, int[] Align)
        {
            if (ColumnName.Length == ColumnWidth.Length && ColumnWidth.Length == Align.Length)
            {
                for (int i = 0; i < ColumnName.Length; i++)
                {
                    if (Align[i] == 0)          //Center Align
                        ListviewName.Columns.Add(new ColHeader(ColumnName[i], ColumnWidth[i], HorizontalAlignment.Center, true));
                    else if (Align[i] == 2)     //Right Align
                        ListviewName.Columns.Add(new ColHeader(ColumnName[i], ColumnWidth[i], HorizontalAlignment.Right, true));
                    else                        //Left Align
                        ListviewName.Columns.Add(new ColHeader(ColumnName[i], ColumnWidth[i], HorizontalAlignment.Left, true));
                }
            }
        }

        //Sự kiện sort listview: comlumn click
        public void EventColumnClick_Listview(ListView listview_name, System.Windows.Forms.ColumnClickEventArgs e, bool sort, bool number)
        {
            // Create an instance of the ColHeader class.
            ColHeader clickedCol = (ColHeader)listview_name.Columns[e.Column];
            // Set the ascending property to sort in the opposite order.

            // Get the number of items in the list.
            int numItems = listview_name.Items.Count;

            // Turn off display while data is repoplulated.
            listview_name.BeginUpdate();

            // Populate an ArrayList with a SortWrapper of each list item.
            ArrayList SortArray = new ArrayList();
            for (int i = 0; i < numItems; i++)
            {
                SortArray.Add(new SortWrapper(listview_name.Items[i], e.Column));
            }

            // Sort the elements in the ArrayList using a new instance of the SortComparer
            // class. The parameters are the starting index, the length of the range to sort,
            // and the IComparer implementation to use for comparing elements. Note that
            // the IComparer implementation (SortComparer) requires the sort
            // direction for its constructor; true if ascending, othwise false.
            //SortArray.Sort(0,SortArray.c
            SortArray.Sort(0, SortArray.Count, new SortWrapper.SortComparer(sort,number));

            // Clear the list, and repopulate with the sorted items.
            listview_name.Items.Clear();
            for (int i = 0; i < numItems; i++)
                listview_name.Items.Add(((SortWrapper)SortArray[i]).sortItem);

            // Turn display back on.
            listview_name.EndUpdate();
        }

        //load dữ liệu từ dataset vào listview không có cột số thứ tự, số format kiểu 1.000
        public void FillListView1(ListView listview, DataSet ds)
        {
            listview.Items.Clear();
            DataRow dr;
            int row = ds.Tables[0].Rows.Count;
            int col = ds.Tables[0].Columns.Count;
            string[] lv = new string[col];
            for (int i = 0; i < row; i++)
            {
                dr = ds.Tables[0].Rows[i];
                for (int j = 0; j < col; j++)
                {
                    //Định dạng ngày tháng năm
                    if (dr[j].GetType() == typeof(DateTime))
                        lv[j] = DateTime.Parse(dr[j].ToString()).ToString("dd/MM/yyyy");
                    //Định dạng số
                    else if (dr[j].GetType() == typeof(Double))
                        lv[j] = FormatCurency(dr[j].ToString());
                    else
                        lv[j] = dr[j].ToString();
                }
                listview.Items.Add(new ListViewItem(lv));
            }
            for (int i = 0; i < listview.Items.Count; i++)
                if (i % 2 == 0)
                    listview.Items[i].BackColor = Color.FromArgb(203, 225, 252);
        }

        //load dữ liệu từ dataset vào listview có cột số thứ tự, số format kiểu 1.000
        public void FillListView2(ListView listview, DataSet ds)
        {
            listview.Items.Clear();
            DataRow dr;
            int row = ds.Tables[0].Rows.Count;
            int col = ds.Tables[0].Columns.Count;
            string[] lv = new string[col + 1];
            for (int i = 0; i < row; i++)
            {
                dr = ds.Tables[0].Rows[i];
                for (int j = 0; j < col; j++)
                {
                    //Định dạng ngày tháng năm
                    if (dr[j].GetType() == typeof(DateTime))
                        lv[j+1] = DateTime.Parse(dr[j].ToString()).ToString("dd/MM/yyyy");
                    //Định dạng số
                    else if (dr[j].GetType() == typeof(Double))
                        lv[j+1] = FormatCurency(dr[j].ToString());
                    else
                        lv[j+1] = dr[j].ToString();
                }
                lv[0] = (i + 1).ToString();
                listview.Items.Add(new ListViewItem(lv));
            }
            for (int i = 0; i < listview.Items.Count; i++)
                if (i % 2 == 0)
                    listview.Items[i].BackColor = Color.FromArgb(203, 225, 252);
        }
        #endregion

        #region Method for Textbox
        //kiểm tra các ký tự đặc biệt
        public bool CheckSpecialCharacter(string s)
        {
            bool kq = true;
            string[] arr = { "`", "~", "!", "#", "$", "%", "^", "&", "*", "(", ")", "=", "+", "\\", "|", "[", "{", "]", "}", ";", ":", "'", "\"", ",", "<", ">", ".", "?", "/" };
            for (int i = 0; i < arr.Length; i++)
            {
                if (s.IndexOf(arr[i]) >= 0)
                    kq = false;
            }
            return kq;
        }

        //kiểm tra email
        public bool CheckEmail(string email)
        {
            bool kq = true;
            int atsym = email.IndexOf('@');
            int period = email.LastIndexOf('.');
            int space = email.IndexOf(' ');
            int l = email.Length - 1;
            if ((atsym < 1) || (period <= atsym + 1) || (period == l) || (space != -1))
                kq = false;
            return kq;
        }

        //kiểm tra website
        public bool CheckWeb(string web)
        {
            bool kq = true;
            int atsym = web.IndexOf('.');
            int period = web.LastIndexOf('.');
            int space = web.IndexOf(' ');
            int l = web.Length - 1;
            if ((atsym < 1) || (period <= atsym + 1) || (period == l) || (space != -1))
                kq = false;
            return kq;
        }

        //readonly textbox
        public void ReadonlyText(TextBox[] textbox_write, TextBox[] textbox_readonly)
        {
            if (textbox_write != null)
                for (int i = 0; i < textbox_write.Length; i++)
                    textbox_write[i].ReadOnly = false;
            if (textbox_readonly != null)
                for (int i = 0; i < textbox_readonly.Length; i++)
                    textbox_readonly[i].ReadOnly = true;
        }

        //Hàm này chỉ cho nhập số, không chấp nhận dấu "."
        //Sử dụng trong sự kiện press
        public void InputNumber(System.Windows.Forms.KeyPressEventArgs e, string str, string strkt)
        {
            if (strkt == "" && e.KeyChar == 48)
                e.Handled = true;
            if (e.KeyChar == 8)
                e.Handled = false;
            else
                if (e.KeyChar < 48 || e.KeyChar > 57)
                    e.Handled = true;
        }

        //Hàm này chỉ cho nhập số, chấp nhận dấu "."
        public void InputNumber(System.Windows.Forms.KeyPressEventArgs e, string str)
        {
            if (e.KeyChar == 8)
                e.Handled = false;
            else
                if (e.KeyChar == 46)
                    e.Handled = false;
                else
                    if (e.KeyChar < 48 || e.KeyChar > 57)
                        e.Handled = true;
        }

        //Hàm chuyển sang định dạng kiểu tiền tệ: 1.000.000
        //Sử dụng trong sự kiện leave
        public string FormatCurency(string st)
        {
            try
            {
                if (st == "" || st.Substring(0, 1) == "0")
                    return "0";
                st = double.Parse(st).ToString("n");
                string ret = st.Substring(0, st.Length - 3);
                return ret;
            }
            catch
            {
                return st;
            }
        }

        //Hàm chuyển sang định dạng kiểu tiền tệ: 1.000.000:00
        public string FormatNumber(string s)
        {
            double d = 0;
            try
            {
                d = double.Parse(s);
                if (d != 0)
                    s = d.ToString("#,#.00");
                else
                    s = "0";
            }
            catch { }
            return s;
        }

        //Hàm hiển thị Hướng dẫn cho textbox
        //Sử dụng trong sự kiện key_up khi nhấn F1
        public void ShowHelpTextbox(TextBox textbox_name, string message, System.Windows.Forms.KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                Help.ShowPopup(textbox_name, message, new Point(textbox_name.Right, textbox_name.Bottom));
            }
        }
        
        //kiem tra la so hay khong
        public bool IsInteger(string s)
        {
            int i = 0;
            try
            {
                i = int.Parse(s);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool IsDouble(string s)
        {
            double d = 0;
            try
            {
                d = double.Parse(s);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string NumberToVNsStringWithUNICODE(string strSo)
        {
            string strTmp = strSo.Replace(".", "").Replace(",", "").Trim();
            string strReturn = "";
            string[] strInit = new string[] { "", "Ngàn", "Triệu", "Tỉ", "Ngàn", "Triệu" };

            try
            {
                double.Parse("0" + strSo);
            }
            catch
            {
                throw new Exception("Error!!! Passed string not is a numeric string.");
            }
            int iCount = 0;
            while (strTmp.Length > 0)
            {
                string strNeedTranslated = "";
                if (strTmp.Length > 3)
                {
                    strNeedTranslated = strTmp.Substring(strTmp.Length - 3);
                    strTmp = strTmp.Substring(0, strTmp.Length - 3);
                }
                else
                {
                    strNeedTranslated = strTmp;
                    strTmp = "";
                }
                string strLink = strTmp;
                string strTranslate = TranslateToVNsWithUNICODE(ref strNeedTranslated, ref strLink);
                if (strTranslate != "")
                    strReturn = strTranslate + " " + strInit.GetValue(iCount).ToString()
                        + (strReturn == "" ? "" : ", ") + strReturn;
                iCount++;
            }
            if (strTmp.Length > 18) throw new Exception("Error!!! Passed string is too lagre numeric string, can not translate.");
            return strReturn;
        }

        public string TranslateToVNsWithUNICODE(ref string strVal, ref string strLink)
        {
            if (double.Parse(strVal) <= 0) return "";
            string strReturn = "";
            string[] arrName = new string[] { "Không", "Một", "Hai", "Ba", "Bốn", "Năm", "Sáu", "Bảy", "Tám", "Chín" };
            string[] arrVal = new string[] { "0", "0", "0" };
            strVal = strVal.Trim();

            for (int iStep = strVal.Length + 1; iStep <= 3; iStep++) strVal = "0" + strVal;

            for (int iStep = 1; iStep <= strVal.Length; iStep++) arrVal.SetValue(strVal.Substring(iStep - 1, 1), iStep - 1);

            strReturn = "";
            if (arrVal.GetValue(0).ToString() != "0")
                strReturn = strReturn + " " + arrName.GetValue(int.Parse(arrVal.GetValue(0).ToString())).ToString() + " Trăm";
            else
            {
                if (strLink == "") strReturn = strReturn;
                else strReturn = strReturn + " Không Trăm";
            }
            if (arrVal.GetValue(1).ToString() != "0")
            {
                if (arrVal.GetValue(2).ToString() != "0")
                {
                    if (arrVal.GetValue(1).ToString() != "1")
                        strReturn = strReturn + " " + arrName.GetValue(int.Parse(arrVal.GetValue(1).ToString())).ToString() + " Mươi";
                    else
                        strReturn = strReturn + " Mười";
                }
                else
                {
                    if (arrVal.GetValue(1).ToString() != "1")
                        strReturn = strReturn + " " + arrName.GetValue(int.Parse(arrVal.GetValue(1).ToString())).ToString() + " Mươi";
                    else
                        strReturn = strReturn + " Mười";
                }
            }
            else
            {
                if (strReturn != "" && arrVal.GetValue(2).ToString() != "0")
                    strReturn = strReturn + " Lẻ";
            }
            if (arrVal.GetValue(2).ToString() != "0")
            {
                if (arrVal.GetValue(2).ToString() != "5" && arrVal.GetValue(2).ToString() != "1")
                    strReturn = strReturn + " " + arrName.GetValue(int.Parse(arrVal.GetValue(2).ToString())).ToString();
                else
                {
                    if (arrVal.GetValue(1).ToString() != "0")
                    {
                        if (arrVal.GetValue(1).ToString() == "1" && arrVal.GetValue(2).ToString() == "1")
                            strReturn = strReturn + " Một";
                        else if (arrVal.GetValue(2).ToString() == "1")
                            strReturn = strReturn + " Mốt";
                        else
                            strReturn = strReturn + " Lăm";
                    }
                    else
                    {
                        strReturn = strReturn + " " + arrName.GetValue(int.Parse(arrVal.GetValue(2).ToString())).ToString();
                    }
                }
            }

            return strReturn.Trim();
        }

        public string NumberToENsStringWithUNICODE(string strSo)
        {
            string strTmp = strSo.Replace(".", "").Replace(",", "").Trim();
            string strReturn = "";
            string[] strInit = new string[] { "", "Thousand", "Million", "Billion", "Thousand", "Million" };

            try
            {
                double.Parse("0" + strSo);
            }
            catch
            {
                throw new Exception("Error!!! Passed string not is a numeric string.");
            }
            int iCount = 0;
            while (strTmp.Length > 0)
            {
                string strNeedTranslated = "";
                if (strTmp.Length > 3)
                {
                    strNeedTranslated = strTmp.Substring(strTmp.Length - 3);
                    strTmp = strTmp.Substring(0, strTmp.Length - 3);
                }
                else
                {
                    strNeedTranslated = strTmp;
                    strTmp = "";
                }
                string strLink = strTmp;
                string strTranslate = TranslateToENsWithUNICODE(ref strNeedTranslated, ref strLink, iCount);
                if (strTranslate != "")
                    strReturn = strTranslate + " " + strInit.GetValue(iCount).ToString()
                        + (strReturn == "" ? "" : ", ") + strReturn;
                iCount++;
            }
            if (strTmp.Length > 18) throw new Exception("Error!!! Passed string is too lagre numeric string, can not translate.");
            return strReturn;
        }

        public string TranslateToENsWithUNICODE(ref string strVal, ref string strLink, int intFlag)
        {
            if (double.Parse(strVal) <= 0) return "";
            string strReturn = "";
            string[] arrName = new string[] { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
            string[] arrNameFrmTen = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
            string[] arrNameFrmTwenty = new string[] { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
            string[] arrVal = new string[] { "0", "0", "0" };
            strVal = strVal.Trim();

            for (int iStep = strVal.Length + 1; iStep <= 3; iStep++) strVal = "0" + strVal;

            for (int iStep = 1; iStep <= strVal.Length; iStep++) arrVal.SetValue(strVal.Substring(iStep - 1, 1), iStep - 1);

            strReturn = "";
            if (arrVal.GetValue(0).ToString() != "0")
            {
                strReturn = strReturn + " " + arrName.GetValue(int.Parse(arrVal.GetValue(0).ToString())).ToString() + " Hundred";
                //In here the intFlag tell that if it is the first group. If it is, add the "and" after hunderd
                if (intFlag == 0 && (arrVal.GetValue(1).ToString() != "0" || arrVal.GetValue(2).ToString() != "0"))
                    strReturn = strReturn + " and ";
            }

            intFlag = 0;
            if (arrVal.GetValue(1).ToString() != "0")
            {
                if (arrVal.GetValue(1).ToString() != "0")
                {
                    if (arrVal.GetValue(1).ToString() != "1")
                        strReturn = strReturn + " " + arrNameFrmTwenty.GetValue(int.Parse(arrVal.GetValue(1).ToString())).ToString();
                    else
                        intFlag = 1; //Telling that will print the array arrNameFrmTen in the third number
                }
            }

            if (arrVal.GetValue(2).ToString() != "0")
            {
                if (intFlag == 1)
                    strReturn = strReturn + " " + arrNameFrmTen.GetValue(int.Parse(arrVal.GetValue(2).ToString())).ToString();
                else
                    strReturn = strReturn + " " + arrName.GetValue(int.Parse(arrVal.GetValue(2).ToString())).ToString();
            }

            return strReturn.Trim();
        }

        public int GetEndDayOfMonth(int month, int year)
        {
            try
            {
                //find end day of current month
                if (month == 12)
                {
                    year = year + 1;
                    month = 1;
                }
                else
                {
                    month = month + 1;
                }
                DateTime dt = new DateTime(year, month, 1);
                DateTime dt1 = dt.AddDays(-1);
                return dt1.Day;
            }
            catch { return 0; }
        }
        #endregion

        #region Method for Control
        //enable va disable cac control
        public void en_dis_control(Control[] en_ctrl, Control[] dis_ctrl)
        {
            if (en_ctrl != null)
                for (int i = 0; i < en_ctrl.Length; i++)
                    en_ctrl[i].Enabled = true;

            if (dis_ctrl != null)
                for (int i = 0; i < dis_ctrl.Length; i++)
                    dis_ctrl[i].Enabled = false;
        }
        //show and visible control
        public void show_visible_control(Control[] show_ctrl, Control[] visible_ctrl)
        {
            if (show_ctrl != null)
                for (int i = 0; i < show_ctrl.Length; i++)
                    show_ctrl[i].Visible = true;

            if (visible_ctrl != null)
                for (int i = 0; i < visible_ctrl.Length; i++)
                    visible_ctrl[i].Visible = false;
        }
        //clear text
        public void ClearText(Control[] ctrl)
        {
            if (ctrl != null)
                for (int i = 0; i < ctrl.Length; i++)
                    ctrl[i].Text = "";
        }

        public DataTable CreateDataTable(string TableName, string[] ColumnName)
        {
            DataTable dataTable = new DataTable(TableName);
            DataColumn col;
            for (int i = 0; i < ColumnName.Length; i++)
            {
                col = new DataColumn();
                col.ColumnName = ColumnName[i];
                dataTable.Columns.Add(col);
            }
            return dataTable;
        }
        #endregion

        #region Method for Security
        //Mã hóa
        public string Encrypt(string s)
        {
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(s);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes("Lam",
                new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = pdb.GetBytes(32);
            alg.IV = pdb.GetBytes(16);
            CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(clearBytes, 0, clearBytes.Length);
            cs.Close();
            return Convert.ToBase64String(ms.ToArray());
        }
        //Giải mã
        public string Decrypt(string s)
        {
            byte[] cipherBytes = Convert.FromBase64String(s);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes("Lam",
                new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });

            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = pdb.GetBytes(32);
            alg.IV = pdb.GetBytes(16);
            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(cipherBytes, 0, cipherBytes.Length);
            cs.Close();
            return System.Text.Encoding.Unicode.GetString(ms.ToArray());
        }
        #endregion

        #region Method for Registry
        public string ReadRegistry(string keyname)
        {
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey skl = rk.OpenSubKey("SOFTWARE\\" + Application.ProductName);

            if (skl == null)
                return null;
            else
            {
                try
                {
                    return (string)skl.GetValue(keyname.ToUpper());
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return null;
                }
            }
        }
        public bool WriteRegistry(string keyname, string keyvalue)
        {
            try
            {
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey skl = rk.CreateSubKey("SOFTWARE\\" + Application.ProductName);
                skl.SetValue(keyname.ToUpper(), keyvalue);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }
        public bool DeleteRegistry(string keyname)
        {
            try
            {
                RegistryKey rk = Registry.LocalMachine;
                RegistryKey skl = rk.CreateSubKey("SOFTWARE\\" + Application.ProductName);
                if (skl == null)
                    return true;
                else
                    skl.DeleteValue(keyname);
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }
        #endregion

        #endregion
    }
}
